console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';

let baseInfoCache;
window.onload = function () {
  window.postMessage({
    event: 'getBaseInfo'
  }, '*');
};

window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    fillInput(await transformDataByOpenWeb(data.data));
  }
  if (data.event === 'getNationData') {
    getNationData();
  }

  if (data.event === 'getBaseInfo') {
    baseInfoCache = data.data;
  }
}, false);

function autoInputAccount({ companyInfo }) {
  // companyInfo = companyInfo || {};
  // Object.assign(companyInfo, {nationalTaxAccount: '13617653551', nationalTaxPass: 'cqzlzw168'});
  // $("#username").val(companyInfo.nationalTaxAccount || companyInfo.nationalTaxId);
  // $("#password").css("display", "inline").val(companyInfo.nationalTaxPass).removeAttr("onblur onfocus");
  // if ($("#password1").length > 0) {
  //   $("#password1").remove()
  // }
}

/**
 * 调用接口获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: '2013', // 国税对应制度 2007 | 2013
    nsrsbh: baseInfoCache.companyInfo.nationalTaxId, // 纳税人申报号
    nsrmc: baseInfoCache.companyInfo.companyName, // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '', // 税款所属期止
    outPutType: 'xml', // 填报方式
    isZip: true,
    filesNum: 3
  };
  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}

function fillInput({ saasData, baseInfo }) {
  let message = '';
  if (saasData.data.type === 'file') {
    message = downloadFile(saasData.data.data, baseInfo);
  } else {
    message = '不支持json方式，下载文件失败！';
  }

  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message || '下载文件成功'
    }
  }, '*');
}

/**
 * 下载文件
 * @param blob
 */
function downloadFile(blob, { companyInfo, taxInfo, popupParams }) {
  blob = new Blob([blob], { type: 'application/vnd.ms-excel' });
  let a = document.createElement('a');
  // 指定生成的文件名
  let name = `${taxInfo.nsrmc}-三大报表-${companyInfo.curYear}-`;
  let curPeriod = companyInfo.curPeriod;
  name += curPeriod.length > 1 ? curPeriod : '0' + curPeriod;
  a.download = `${name}.zip`;
  a.href = URL.createObjectURL(blob);
  document.body.appendChild(a);
  a.click();
}
